package com.cryptape.cita_wallet.activity;

import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cryptape.cita_wallet.CytonApplication;
import com.cryptape.cita_wallet.activity.transfer.EntrustTransferPresenter;
import com.cryptape.cita_wallet.activity.transfer.TransferActivity;
import com.cryptape.cita_wallet.bean.MortgageMining;
import com.cryptape.cita_wallet.bean.MortgageMiningBean;
import com.cryptape.cita_wallet.bean.MyMIDBean;
import com.cryptape.cita_wallet.constant.ConstantUtil;
import com.cryptape.cita_wallet.event.RefreshMidEvent;
import com.cryptape.cita_wallet.item.Token;
import com.cryptape.cita_wallet.net.callback.CommonCallback;
import com.cryptape.cita_wallet.net.request.HttpRequestMode;
import com.cryptape.cita_wallet.service.ContractService;
import com.cryptape.cita_wallet.service.http.EthRpcService;
import com.cryptape.cita_wallet.service.http.TokenService;
import com.cryptape.cita_wallet.util.NumberUtil;
import com.cryptape.cita_wallet.util.RSAUtils;
import com.cryptape.cita_wallet.util.db.DBWalletUtil;
import com.cryptape.cita_wallet.util.ether.EtherUtil;
import com.cryptape.cita_wallet.view.dialog.ToastSingleButtonDialog;
import com.cryptape.cita_wallet.view.dialog.listener.OnDialogOKClickListener;
import com.mangoworld.android.R;

import org.greenrobot.eventbus.EventBus;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

;

/**
 * Created by dengming on 11/1/20.
 */

public class ChiBiActivity extends NBaseActivity {
    private RelativeLayout rl_entrust;
    private RelativeLayout rl_ransom;
    private TextView tv_yesterdayPool;
    private TextView tv_sysMgpNum;
    private TextView tv_nowDayCalPower;
    private TextView tv_yesterdayPoolCalPower;
    private TextView tv_yesterdayMoney;
    //    private TextView nowPool;
    private TextView tv_orderName;
    private TextView tv_additionPower;
    private TextView orderMoney;
    private TextView tv_yesterdayAllCalPower;

    private TextView tv_order_value_yesterday;
    private TextView tv_yesterday_excitation;
    private TextView tv_incentive_index;
    private TextView tv_my_mortgage_level;
    private TextView tv_mortgage_value;
    private TextView tv_mortgage_amount;
    private TextView tv_mortgage_status;
    private TextView tv_mortgage_time;
    private TextView tv_expected_to_unlock;
    private TextView tv_coin_day_value;

    private LockInfo mLockInfo = null;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_chibi;
    }

    @Override
    protected void initView() {
        rl_entrust = (RelativeLayout) findViewById(R.id.rl_entrust);
        rl_ransom = (RelativeLayout) findViewById(R.id.rl_ransom);

        tv_yesterdayPool = (TextView) findViewById(R.id.tv_myFloor);
        tv_sysMgpNum = (TextView) findViewById(R.id.tv_sysMgpNum);
        tv_nowDayCalPower = (TextView) findViewById(R.id.tv_nowDayCalPower);

        tv_yesterdayPoolCalPower = (TextView) findViewById(R.id.tv_yesterdayPoolCalPower);
        tv_yesterdayMoney = (TextView) findViewById(R.id.tv_yesterdayMoney);
//        nowPool = (TextView) findViewById(R.id.nowPool);
        tv_orderName = (TextView) findViewById(R.id.tv_orderName);
        tv_additionPower = (TextView) findViewById(R.id.tv_additionPower);
        orderMoney = (TextView) findViewById(R.id.orderMoney);
        tv_yesterdayAllCalPower = (TextView) findViewById(R.id.tv_yesterdayAllCalPower);

        tv_order_value_yesterday = (TextView) findViewById(R.id.tv_order_value_yesterday);
        tv_yesterday_excitation = (TextView) findViewById(R.id.tv_yesterday_excitation);
        tv_incentive_index = (TextView) findViewById(R.id.tv_incentive_index);
        tv_my_mortgage_level = (TextView) findViewById(R.id.tv_my_mortgage_level);

        tv_mortgage_value = (TextView) findViewById(R.id.tv_mortgage_value);
        tv_mortgage_amount = (TextView) findViewById(R.id.tv_mortgage_amount);
        tv_mortgage_status = (TextView) findViewById(R.id.tv_mortgage_status);
        tv_mortgage_time = (TextView) findViewById(R.id.tv_mortgage_time);
        tv_expected_to_unlock = (TextView) findViewById(R.id.tv_expected_to_unlock);
        tv_coin_day_value = (TextView) findViewById(R.id.tv_coin_day_value);
    }

    @Override
    protected void initData() {
        updateContract();
    }

    private void updateLockInfo() {
        Observable.fromCallable(new Callable<String>() {
            @Override
            public String call() throws Exception {
                List<Type> datas = ContractService.lockAddress();
                if (datas != null && datas.size() == 1) {
                    return ((Address) datas.get(0)).getValue();
                }
                return null;
            }
        }).flatMap(new Func1<String, Observable<List<Type>>>() {
            @Override
            public Observable<List<Type>> call(String o) {
                return Observable.fromCallable(new Callable<List<Type>>() {
                    @Override
                    public List<Type> call() throws Exception {
                        if (o == null || o.equals("0x0000000000000000000000000000000000000000")) {
                            return null;
                        }
                        List<Type> datas = ContractService.orderDetail(o);
                        return datas;
                    }
                });
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<Type>>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        mTransferView.transferEtherFail("获取地址失败");
                    }

                    @Override
                    public void onNext(List<Type> datas) {
                        {
                            if (datas != null && datas.size() > 1) {
                                String type = null;
                                BigInteger lockType = ((Uint256) datas.get(0)).getValue();
                                BigInteger natureType = (BigInteger.ONE);
                                BigInteger mixType = (new BigInteger("2"));
                                BigInteger emptyType = (new BigInteger("3"));
                                if (lockType.compareTo(natureType) == 0) {
                                    type = EntrustTransferPresenter.TYPE_LOCK_NATURE;
                                } else if (mixType.compareTo(lockType) == 0) {
                                    type = EntrustTransferPresenter.TYPE_LOCK_MIX;
                                } else if (emptyType.compareTo(lockType) == 0) {
                                    type = EntrustTransferPresenter.TYPE_LOCK_EMPTY;
                                }
                                BigInteger balance = ((Uint256) datas.get(1)).getValue();
                                double num = NumberUtil.getEthFromWei(balance);

                                tv_orderName.setText(getString(R.string.Type) + type);// = (TextView) findViewById(R.id.tv_orderName);

//
//  tv_additionPower.setText(getString(R.string.Hold_Time)+s.getData().getAdditionPower());// = (TextView) findViewById(R.id.tv_additionPower);
                                StringBuilder numSb = new StringBuilder();
                                numSb.append(num);
                                if (num >= 10000) {
                                    numSb.append("(M4)");
                                } else if (num >= 5000) {
                                    numSb.append("(M3)");
                                } else if (num >= 2000) {
                                    numSb.append("(M2)");
                                } else if (num >= 500) {
                                    numSb.append("(M1)");
                                }
                                orderMoney.setText(getString(R.string.my_weituo) + numSb.toString());
                            } else {

                            }
                        }
                    }
                });
    }

    private void checkMidExist(int id) {
        try {
            String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
            Map params = MapUtils.newHashMap();
            params.put("address", address);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.findMid(ChiBiActivity.this, content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    MyMIDBean midBean = (MyMIDBean) data;

                    if (midBean != null) {
                        String mid = midBean.getLnvitationCode();
                        CytonApplication.getInstance().MIDCode = mid;
                        if (TextUtils.isEmpty(mid)) {
                            Toast.makeText(ChiBiActivity.this, getString(R.string.tip_please_active), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        EventBus.getDefault().post(new RefreshMidEvent());
                        if (id == R.id.rl_entrust) {
                            Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
                            Intent intent = new Intent(ChiBiActivity.this, EntrustNewActivity.class);
                            token.setContractAddress(ConstantUtil.getMGPToken());
                            token.decimals = 18;
                            intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
                            intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.getDEPOSITCONTRACT());
                            startActivity(intent);
                        } else if (id == R.id.rl_ransom) {
                            gotoRansom();
                        }
                    } else {
                        CytonApplication.getInstance().MIDCode = "";
                    }

                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    CytonApplication.getInstance().MIDCode = "";
                    Toast.makeText(ChiBiActivity.this, getString(R.string.tip_please_active), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void gotoRansom() {
        if (mLockInfo == null) {
            return;
        }
        if (mLockInfo.getBackType() == 2) {
            Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
            Intent intent = new Intent(ChiBiActivity.this, RansomActivity.class);
            intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
            token.setContractAddress(ConstantUtil.getHToken());
            token.decimals = 18;
            intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.getDEPOSITCONTRACT());
            startActivity(intent);
            return;
        }
        if (mLockInfo.getBackType() == 1) {
            Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
            Intent intent = new Intent(ChiBiActivity.this, GetBackCoinActivity.class);
            intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
            token.setContractAddress(ConstantUtil.getHToken());
            token.decimals = 18;
            if (mLockInfo.aTokenBalance != null && mLockInfo.aTokenBalance.compareTo(BigInteger.ZERO) > 0) {
                intent.putExtra(GetBackCoinActivity.ATOKENBALANCE, String.valueOf(NumberUtil.getEthFromWei(mLockInfo.aTokenBalance)));
            }
            if (mLockInfo.bTokenBalance != null && mLockInfo.bTokenBalance.compareTo(BigInteger.ZERO) > 0) {
                intent.putExtra(GetBackCoinActivity.BTOKENBALANCE, String.valueOf(NumberUtil.getEthFromWei(mLockInfo.bTokenBalance)));
            }
            startActivity(intent);
            return;
        }
    }

    @Override
    protected void initAction() {
        rl_entrust.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(ChiBiActivity.this,getString(R.string.Not_open_yet),Toast.LENGTH_SHORT).show();
                if (TextUtils.isEmpty(CytonApplication.getInstance().MIDCode)) {
                    checkMidExist(R.id.rl_entrust);
                    return;
                }
                Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
                Intent intent = new Intent(ChiBiActivity.this, EntrustNewActivity.class);
                token.setContractAddress(ConstantUtil.getMGPToken());
                token.decimals = 18;
                intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
                intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.getDEPOSITCONTRACT());
                startActivity(intent);
            }
        });

        rl_ransom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(ChiBiActivity.this,getString(R.string.Not_open_yet),Toast.LENGTH_SHORT).show();

                if (TextUtils.isEmpty(CytonApplication.getInstance().MIDCode)) {
                    checkMidExist(R.id.rl_ransom);
                    return;
                }
                gotoRansom();
//                Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
//                Intent intent = new Intent(ChiBiActivity.this, RansomActivity.class);
//                intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
//                token.setContractAddress(ConstantUtil.getHToken());
//                token.decimals = 18;
//                intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.getDEPOSITCONTRACT());
//                startActivity(intent);
            }
        });
    }

    private void updateContract() {
        showProgressBar();
        Observable.fromCallable(() -> {
            String result = ContractService.updateContract();
            return result;
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressBar();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressBar();
            }

            @Override
            public void onNext(String result) {
                dismissProgressBar();
                LogUtils.dTag("MainActivity==", "result = " + result + " contract = " + ConstantUtil.getDEPOSITCONTRACT());
                if (ObjectUtils.equals("fail", result)) {
                    ToastSingleButtonDialog dialog = ToastSingleButtonDialog
                            .getInstance(ChiBiActivity.this, getString(R.string.str_network_anomaly), getString(R.string.str_network_anomaly_msg));
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.setOnCancelClickListener(new OnDialogOKClickListener() {
                        @Override
                        public void onClick(Dialog dialog) {
                            finish();
                        }
                    });
                } else {
                    getMortgageMining();
                    totalSupply();
                }
            }
        });
    }

    private void getMortgageMining() {
        String address = DBWalletUtil.getCurrentWallet(CytonApplication.getInstance()).address;
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", address);
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            HttpRequestMode.getOrderIndex(ChiBiActivity.this, content, true, new CommonCallback() {
                @Override
                public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                    queryLockData();

                    if (data == null) {
                        return;
                    }
                    MortgageMiningBean mortgageMining = (MortgageMiningBean) data;
                    tv_sysMgpNum.setText(mortgageMining.getSysMgpNum());
                    MortgageMining.Order order = mortgageMining.getOrder();
                    if (order != null) {
                        tv_my_mortgage_level.setText(order.getOrderLevel());
                        if (order.getMgpNum() == null) {
                            findViewById(R.id.ll_mortgage_amount).setVisibility(View.GONE);
                        } else {
                            String mgpNum = order.getMgpNum();
                            tv_mortgage_amount.setText((ObjectUtils.isEmpty(mgpNum) == true ? "0" : mgpNum) + "MGP");
                            tv_mortgage_value.setText("$" + order.getOrderValue());
                        }

                        tv_mortgage_status.setText(order.getLockStatus() == null ? "" : order.getLockStatus());
                        tv_mortgage_time.setText(order.getCreateTime() == null ? "" : order.getCreateTime());
//                tv_expected_to_unlock.setText(order.get);
                        if (order.getUnlockTime() == null) {
                            findViewById(R.id.ll_to_unlock).setVisibility(View.GONE);
                        } else {
                            tv_expected_to_unlock.setText(order.getUnlockTime());
                        }
                        String dailyPro = order.getDailyPro();
                        String mDailyPro = null;
                        if (!ObjectUtils.isEmpty(dailyPro)) {
                            BigDecimal dailyProDecimal = new BigDecimal(dailyPro);
                            mDailyPro = dailyProDecimal.multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString();
                        }
                        tv_coin_day_value.setText(mDailyPro == null ? "" : (mDailyPro + "%"));
                    }
                    MortgageMining.YesterdayOrder yesterdayOrder = mortgageMining.getYesterdayOrder();
                    if (yesterdayOrder != null) {
                        tv_order_value_yesterday.setText(yesterdayOrder.getOrderValue());
                        tv_yesterday_excitation.setText((yesterdayOrder.getMoney() == null ? "0" : yesterdayOrder.getMoney()) + "ETH");
                        tv_incentive_index.setText(yesterdayOrder.getPro() + "%");
                    }
                }

                @Override
                public void onFailure(String msg, int responseFailCode) {
                    ToastUtils.showLong(getString(R.string.withdrawal_fail));
                    queryLockData();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void totalSupply() {
        EthRpcService.totalSupply().subscribe(new Subscriber<BigInteger>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(BigInteger data) {
                if (data != null) {
                    if (EtherUtil.getEthNodeName().equals(ConstantUtil.ETH_ROPSTEN_NAME)) {
                        BigInteger left = new BigInteger("5000000000").subtract(data);
                        tv_nowDayCalPower.setText(left.toString());
                    } else {
                        BigInteger left = new BigInteger("500000000").subtract(data);
                        tv_nowDayCalPower.setText(left.toString());
                    }
                }
            }
        });
    }

    private void queryLockData() {
        showProgressBar();
        Observable.fromCallable(new Callable<LockInfo>() {
            @Override
            public LockInfo call() throws Exception {
                LockInfo lockInfo = new LockInfo();
                List<Type> datas = ContractService.lockAddress();

                if (datas == null || datas.size() == 0) {
                    lockInfo.lockAddress = null;
                }
                String address = ((Address) datas.get(0)).getValue();
                if (address == null || address.equals("0x0000000000000000000000000000000000000000")) {
                    lockInfo.lockAddress = null;
                }
                List<Type> orderTypes = ContractService.orderDetail(address);

                if (orderTypes == null || orderTypes.size() == 0) {
                    lockInfo.type = null;
                } else {
                    String type = null;
                    BigInteger lockType = ((Uint256) orderTypes.get(0)).getValue();
                    BigInteger natureType = (BigInteger.ONE);
                    BigInteger mixType = (new BigInteger("2"));
                    BigInteger emptyType = (new BigInteger("3"));
                    if (lockType.compareTo(natureType) == 0) {
                        type = EntrustTransferPresenter.TYPE_LOCK_NATURE;
                    } else if (mixType.compareTo(lockType) == 0) {
                        type = EntrustTransferPresenter.TYPE_LOCK_MIX;
                    } else if (emptyType.compareTo(lockType) == 0) {
                        type = EntrustTransferPresenter.TYPE_LOCK_EMPTY;
                    }
                    lockInfo.type = type;
                }
                List<Type> aBalance = ContractService.aTokenBalance();
                if (aBalance != null && aBalance.size() > 0) {
                    BigInteger balance1 = ((Uint256) aBalance.get(0)).getValue();
                    Log.e("MainActivity", "A Balance:" + balance1.toString());
                    lockInfo.aTokenBalance = balance1;
                }

                List<Type> bBalance = ContractService.bTokenBalance();
                if (bBalance != null && bBalance.size() > 0) {
                    BigInteger balance2 = ((Uint256) bBalance.get(0)).getValue();
                    Log.e("MainActivity", "B Balance:" + balance2.toString());
                    lockInfo.bTokenBalance = balance2;
                }
                return lockInfo;
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LockInfo>() {
                    @Override
                    public void onCompleted() {
                        dismissProgressBar();
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgressBar();
                    }

                    @Override
                    public void onNext(LockInfo lockInfo) {
                        if (lockInfo == null) {
                            return;
                        }
                        mLockInfo = lockInfo;
                        if (lockInfo == null || lockInfo.getBackType() == 0) {
                            rl_ransom.setVisibility(View.GONE);
                            rl_entrust.setVisibility(View.GONE);
                        } else {
                            rl_ransom.setVisibility(View.VISIBLE);
                            TextView tv_ransom = rl_ransom.findViewById(R.id.tv_ransom);
                            if (lockInfo.getBackType() == 1) {
                                tv_ransom.setText(getString(R.string.get_back));
                            } else if (lockInfo.getBackType() == 2) {
                                tv_ransom.setText(getString(R.string.Withdrawal));
                            }
                        }
//                        if (TextUtils.isEmpty(lockInfo.type)
//                                && !lockInfo.hasTokenBalance()) {
//                            rl_ransom.setVisibility(View.GONE);
//                        } else if ()
//                            if (TextUtils.isEmpty(lockInfo.type)) {
//                                rl_ransom.setVisibility(View.GONE);
//                            } else {
//                                rl_ransom.setVisibility(View.VISIBLE);
//                            }
                        TextView tv_mortgage = findViewById(R.id.tv_mortgage);
                        rl_entrust.setVisibility(View.VISIBLE);
                        if (TextUtils.isEmpty(lockInfo.type)) {
                            if ((lockInfo.aTokenBalance != null && lockInfo.aTokenBalance.compareTo(BigInteger.ZERO) > 0) ||
                                    (lockInfo.bTokenBalance != null && lockInfo.bTokenBalance.compareTo(BigInteger.ZERO) > 0)) {
                                tv_mortgage.setText(getString(R.string.Deposit_confirm));
                            } else {
                                tv_mortgage.setText(getString(R.string.Deposit));
                            }
                        } else {
                            if ((lockInfo.aTokenBalance != null && lockInfo.aTokenBalance.compareTo(BigInteger.ZERO) > 0) ||
                                    (lockInfo.bTokenBalance != null && lockInfo.bTokenBalance.compareTo(BigInteger.ZERO) > 0)) {
                                tv_mortgage.setText(getString(R.string.append));
                            } else {
                                tv_mortgage.setText(getString(R.string.append_initiate));
                            }
                        }
                    }
                });
    }

    class LockInfo {
        public String lockAddress;
        public String type;
        public BigInteger aTokenBalance;
        public BigInteger bTokenBalance;

        public boolean hasTokenBalance() {
            if (aTokenBalance != null && aTokenBalance.compareTo(BigInteger.ZERO) > 0
                    || (bTokenBalance != null && bTokenBalance.compareTo(BigInteger.ZERO) > 0)) {
                return true;
            }
            return false;
        }

        public int getBackType() {
            if (TextUtils.isEmpty(type) && !hasTokenBalance()) {
                return 0;
            }
            if ((!TextUtils.isEmpty(type) && hasTokenBalance())
                    || (TextUtils.isEmpty(type) && hasTokenBalance())) {
                return 1;
            }

            if (!TextUtils.isEmpty(type) && !hasTokenBalance()) {
                return 2;
            }
            return 0;
        }
    }
}
